//创建一个链式栈 并实现栈的基本操作

#include <stdio.h>
#include <stdlib.h>
//定义栈节点
typedef struct Node{
    int data;
    struct Node *next;
}Node;
//定义栈
typedef struct Stack{
    Node *top;
    int size;//栈大小
}Stack;
//初始化栈
void initStack(Stack *stack);
//入栈
int push(Stack *stack, int data);
//出栈
int pop(Stack *stack,int *value);
//获取栈顶元素
//获取栈顶元素
int top(Stack stack,int *value);
//判断栈是否为空
int isEmpty(Stack stack);
//销毁栈

int destroyStack(Stack *stack);
//求栈的大小
int getstack_size(Stack stack);
//打印栈
void printStack(Stack *stack);
int main(int argc, char const *argv[])
{
    Stack  linkstack;;//
    initStack(&linkstack);//初始化栈
    //入栈
    push(&linkstack,1);
    push(&linkstack,2);
    push(&linkstack,3);
    push(&linkstack,4);
    printf("栈的大小为：%d\n", getstack_size(linkstack));
     //打印
    printStack(&linkstack);
    //出栈
    int dat;
    if(!pop(&linkstack,&dat))printf("出栈数据：%d\n",dat);else printf("stack pop is error\n ");
    if(!pop(&linkstack,&dat))printf("出栈数据：%d\n",dat);else printf("stack pop is error\n ");
    if(!pop(&linkstack,&dat))printf("出栈数据：%d\n",dat);else printf("stack pop is error\n ");
    if(!pop(&linkstack,&dat))printf("出栈数据：%d\n",dat);else printf("stack pop is error\n ");
    if(!pop(&linkstack,&dat))printf("出栈数据：%d\n",dat);else printf("stack pop is error\n ");
    //销毁
    destroyStack(&linkstack);
    printf("栈的大小为：%d\n", getstack_size(linkstack));

    /* code */
    return 0;
}

//初始化栈
void initStack(Stack *stack)
{
    stack->top=NULL;//空栈
    stack->size=0;
}
//入栈
int push(Stack *stack, int data)
{
    //创建一个新的结点
    Node *newnode =(Node *)malloc(sizeof(Node));
    if(newnode==NULL)
    {
        return -1;
    }
    newnode->data=data;
    newnode->next=NULL;
    //修改指针
    //将新结点 放在栈顶（表头）
    newnode->next=stack->top;
    stack->top=newnode;
    stack->size++;//加了一个数据
    return 0;
}
//出栈
int pop(Stack *stack,int *value)
{
    if(isEmpty(*stack))
    {
        return 1;
    }
    //从表头开始出来
    *value=stack->top->data;
    Node * temp=stack->top;//先保存栈顶结点
    //更新一下栈顶
    stack->top=temp->next;
    //释放之前的栈顶
    free(temp);
    stack->size--;
    return 0;
}
//获取栈顶元素
int top(Stack stack,int *value)
{
    if(isEmpty(stack))
    {
       return 1; 
    }
    *value=stack.top->data;
    return 0;
}
//判断栈是否为空
int isEmpty(Stack stack)
{
    return stack.top==NULL;
}
//销毁栈
int destroyStack(Stack *stack)
{
    if(isEmpty(*stack))
    {
       return 1; 
    }
    Node *temp=stack->top;
    while (temp!=NULL)
    {
        stack->top=temp->next;
        free(temp);
        stack->size--;
        temp=stack->top;
    }
    return 0;

}
//打印栈
void printStack(Stack* stack)
{
    if(isEmpty (*stack))
    {
        return;
    }

    Node *temp=stack->top;
    while (temp!= NULL)
    {
       printf("%d \n",temp->data);
       temp=temp->next;
    }
    printf("\n");

}
//求栈的大小
int getstack_size(Stack stack)
{
    return stack.size;
}